*
*   IEA -- for calculating numbers from IEA
*
*

* Make sure directory is set to LDAR_RCT_replication_package


************* Programs:

* For writing something (the `anything') that is not enclosed by double quotes:
cap program drop write_single_num
program define write_single_num
	syntax anything, Filename(string)
	cap erase "`filename'"
	cap file close temp_file
	file open temp_file using "`filename'", write
	file write temp_file "`anything'"
	file close temp_file

end

* For writing something (the `anything') that IS enclosed by double quotes:
cap program drop write_single_string
program define write_single_string
	syntax anything, Filename(string)
	cap erase "`filename'"
	cap file close temp_file
	file open temp_file using "`filename'", write
	file write temp_file `anything'
	file close temp_file

end


***************************************************

* Abatement data - 2023 -- fraction of leaks with negative abatement costs:


insheet  using "Data/Raw/IEA/Methane_Tracker_2023/IEA-methane-abatement-OILGASdata-.csv", clear


keep if inlist(abatement, "Upstream LDAR", "Downstream LDAR")

gen negative_abatement_cost = cost < 0

qui sum savings 
di  %12.0fc r(N)*r(mean)
local total_savings = r(N)*r(mean)

qui sum savings if negative_abatement_cost == 1
di %12.0fc r(N)*r(mean)
local total_savings_negative = r(N)*r(mean)

qui sum savings if abatement == "Upstream LDAR"
di %12.0fc r(N)*r(mean)
local upstream_total_savings = r(N)*r(mean)

qui sum savings if abatement == "Upstream LDAR" & negative_abatement_cost == 1
di %12.0fc r(N)*r(mean)
local upstream_total_savings_negative = r(N)*r(mean)

local frac_negative = string(round(100*`upstream_total_savings_negative'/`upstream_total_savings'), "%3.0f")

write_single_num `frac_negative', file("Paper/Figures/single_numbers/iea_fraction_negative_abatement_cost.tex") 


***************************************************

* Emissions data - 2023 -- computing fraction that are leaks:

insheet  using "Data/Raw/IEA/Methane_Tracker_2023/IEA-MethaneEmissionsComparison-World.csv", clear

* Limits it to energy
keep if type == "Energy"

drop if segment == "Total" // these are sums; not dropping them would lead to double counting

* keeps only upstream oil-and-gas related stuff
keep if inlist(segment, "Offshore gas", "Offshore oil", "Onshore gas", "Onshore oil", "Gas pipelines and LNG facilities")

qui sum emissions
local categorizable_emissions = r(N)*r(mean)
qui sum emissions if reason == "Fugitive"
local leaked_emissions = r(N)*r(mean)
qui sum emissions if reason == "Vented"
local vented_emissions = r(N)*r(mean)

local frac_leaks = string(round(100*`leaked_emissions'/`categorizable_emissions'))
write_single_num `frac_leaks', file("Paper/Figures/single_numbers/iea_fraction_leaks.tex") 















